// pages/publish/publish.js
const db = wx.cloud.database().collection('house_information')
Page({

  /**
   * 页面的初始数据
   */
  data: {

    region: ['北京市', '北京市', '东城区'],
    tempFilePaths: [],
    houseName: '',
    location: '',
    storey: '',
    area: '',
    orientation: '',
    layout: '',
    rent: '',
    describe: '',
    pics: [],
    imgbox: '',//用于上传图片
    max: 300,//文本框区域最大限度为300
    currentWordNumber: 0//文本框当前字数为0

  },

  // 选择省市区
  onRegionChange(e) {
    // console.log(e);
    this.setData({
      region: e.detail.value
    })
  },

  // 表单提交
  formSubmit: function (e) {
    this.uploadPic();
    this.setData({
      houseName: e.detail.value.houseName,
      location: this.data.region[0] + this.data.region[1] + this.data.region[2] + e.detail.value.location,
      storey: e.detail.value.storey,
      area: e.detail.value.area,
      orientation: e.detail.value.orientation,
      layout: e.detail.value.layout,
      rent: e.detail.value.rent,
      describe: e.detail.value.describe
    })
    setTimeout(() => {
      this.uploadInfo();
    }, 1200 * this.data.tempFilePaths.length);
  },

  // 添加图片
  addPic(e) {
    // console.log(e);
    var imgbox = this.data.imgbox;
    // console.log(imgbox)
    var picid = e.currentTarget.dataset.pic;
    // console.log(picid)
    var that = this;
    var n = 6;
    if (6 > imgbox.length > 0) {
      n = 6 - imgbox.length;
    } else if (imgbox.length == 6) {
      n = 1;
    }
    wx.chooseImage({
      count: n, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // console.log(res.tempFilePaths)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        if (imgbox.length == 0) {
          imgbox = res.tempFilePaths
        } else if (9 > imgbox.length) {
          imgbox = imgbox.concat(res.tempFilePaths);
        } else {
          imgbox[picid] = res.tempFilePaths[0];
        }
        that.setData({
          tempFilePaths: res.tempFilePaths,
          imgbox: imgbox
        });
      }
    })
  },

  // 上传图片
  uploadPic() {
    let fileName = `${Date.now()}_${Math.floor(Math.random(0, 1) * 10000000)}`
    var pics = []
    var that = this
    var tempFilePaths = this.data.tempFilePaths;
    for (var i = 0; i < tempFilePaths.length; i++) {
      wx.cloud.uploadFile({
        cloudPath: fileName + '.png', // 上传至云端的路径
        filePath: tempFilePaths[i], // 小程序临时文件路径
        success: res => {
          pics.push(res.fileID)
        },
      })
    }
    setTimeout(() => {
      that.setData({
        pics: pics
      })
    }, 1200 * this.data.tempFilePaths.length);
  },

  // 上传信息
  uploadInfo() {
    db.add({
      data: {
        title: this.data.houseName,
        location: this.data.location,
        storey: this.data.storey,
        area: this.data.area,
        orientation: this.data.orientation,
        layout: this.data.layout,
        rent: this.data.rent,
        describe: this.data.describe,
        image_src: this.data.pics[0],
        pics: this.data.pics
      },
      success() {
        wx.showToast({
          title: '发布成功',
          icon: 'success',
          mask: true
        })
          .then(res => {
            setTimeout(() => {
              wx.navigateTo({
                url: '/pages/publish/publish'
              });
            }, 1000);
          });
      },
      fail() {
        wx.showToast({
          title: '发布失败',
          icon: 'error',
          mask: true
        });
      }
    })
  },

  // 监听textarea的字数限制和动态变化
  onDescribeInput(e) {
    // 获取输入框的内容
    var value = e.detail.value;
    // 获取输入框内容的长度
    var len = parseInt(value.length);

    //最多字数限制
    if (len > this.data.max) return;
    // 当输入框内容的长度大于最大长度限制（max)时，终止setData()的执行
    this.setData({
      currentWordNumber: len //当前字数  
    });
  },

  // 删除照片
  imgDelete: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.deindex;
    let imgbox = this.data.imgbox;
    imgbox.splice(index, 1)
    that.setData({
      imgbox: imgbox
    });
  }
})